#include <iostream>
#include <string>
#include "muduo/net/TcpClient.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/net/TcpConnection.h"
#include "muduo/net/Buffer.h"
#include "muduo/base/CountDownLatch.h"


class DictClient
{
public:
    DictClient(const std::string& ip, int port)
        :_baseloop(_loopthread.startLoop())
        ,_downlatch(1)
        ,_client(_baseloop, muduo::net::InetAddress(ip, port), "DictClient")
    {
        // 设置连接处理的回调
        _client.setConnectionCallback(std::bind(&DictClient::onConnection, this, std::placeholders::_1));
        // 设置消息处理的回调
        _client.setMessageCallback(std::bind(&DictClient::onMessage,this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        // 连接服务器 connect()是异步操作，是非阻塞的
        _client.connect();
        // _downlatch.wait() 的目的是：让构造函数阻塞，直到连接操作有结果（成功或失败）后再返回。
        _downlatch.wait();
    }

    void send(const std::string& msg)
    {
        if(_conn->connected() == false)
        {
            std::cout << "连接已经断开, 发送数据失败" << std::endl;
        }
        else
        {
            _conn->send(msg);
        }
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            std::cout << "连接建立成功" << std::endl;
            _downlatch.countDown(); // 计数--,为0时唤醒阻塞
            _conn = conn;
        }
        else
        {
            std::cout << "连接建立失败" << std::endl;
            _conn.reset();
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr conn, muduo::net::Buffer* buffer, muduo::Timestamp)
    {
        std::string res = buffer->retrieveAllAsString();
        std::cout << res << std::endl;
    }

private:
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _downlatch;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::EventLoop* _baseloop;
    muduo::net::TcpClient _client;
};

int main()
{
    DictClient client("127.0.0.1", 9090);
    while(1) {
        std::string msg;
        std::cin >> msg;
        client.send(msg);
    }
    return 0;
}